package com.qianfeng.zhangwei.windowmanager;

import android.content.Context;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import com.qianfeng.zhangwei.R;

/**
 * @说 明：
 * @项目名称：Sz1504Adv
 * @包 名： com.qianfeng.zhangwei
 * @类 名： FloatView
 * @创 建人： zhangwei
 * @创建时间：2015-08-12 14:48
 * @版 本：v1.0
 * @修 改人：
 * @修改时间：
 * @修改备注：
 */
public class FloatView extends ImageView {
    private WindowManager.LayoutParams params;
    private int statusHeight = 0;


    public FloatView(Context context) {
        super(context);
        statusHeight = getStatusHeight(context);
        init();
    }

    private void init() {
        setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        setImageResource(R.mipmap.ic_launcher);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int width = this.getWidth();
        int height = this.getHeight();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_MOVE:
                int rawX = (int) event.getRawX();
                int rawY = (int) event.getRawY() - statusHeight;
                updateLayout(rawX - (width / 2), rawY - height / 2);
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return super.onTouchEvent(event);
    }


    public void updateLayout(int x, int y) {
        params.x = x;
        params.y = y;
        WindowManagerUtils.getInstance().getWindowManager().updateViewLayout(this, params);
    }

    public int getStatusHeight(Context context) {
        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = getContext().getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;

    }


    public WindowManager.LayoutParams getParams() {
        return params;
    }

    public void setParams(WindowManager.LayoutParams params) {
        this.params = params;
    }
}
